#include <iostream>
using namespace std;
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <cstring>
#include <netinet/in.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <strings.h>
#include <pthread.h>

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n"
              << std::endl;
}
struct Datatype
{
    struct sockaddr_in server;
    int sockfd_;
};
void *recvMessage(void *args)
{
    struct Datatype *t = static_cast<struct Datatype *>(args);
    char buffer[1024];

    while (true)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        ssize_t s = recvfrom(t->sockfd_, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&client, &len);
        if (s > 0)
        {
            buffer[s] = 0;
            cerr << buffer << endl;
        }
    }
}

void *sendMessage(void *args)
{
    struct Datatype *t = static_cast<struct Datatype *>(args);
    string message;
    socklen_t len = sizeof(t->server);
    while (true)
    {
        cout << "Please Enter@ ";
        getline(cin, message);

        ssize_t n = sendto(t->sockfd_, message.c_str(), message.size(), 0, (const struct sockaddr *)&(t->server), len);
        sleep(1);
    }
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }

    struct Datatype t;

    uint16_t port_ = stoi(argv[2]);
    string serverip = argv[1];
    bzero(&t.server, sizeof(t.server));
    t.server.sin_family = AF_INET;
    t.server.sin_addr.s_addr = inet_addr(serverip.c_str());
    t.server.sin_port = htons(port_);
    t.sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
    if (t.sockfd_ < 0)
    {
        cout << "socket fail" << endl;
        return 1;
    }
    cout << "socket success" << endl;

    pthread_t recv_t, send_t;
    pthread_create(&recv_t, NULL, recvMessage, &t); // 接收消息

    pthread_create(&send_t, NULL, sendMessage, &t); // 发消息

    pthread_join(recv_t, NULL);

    pthread_join(send_t, NULL);
    close(t.sockfd_);
}